package com.zzg.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzg.srb.core.entity.pojo.Dict;
import com.zzg.srb.core.entity.dto.ExcelDictDTO;
import com.zzg.srb.core.listener.ExcelDictDTOListener;
import com.zzg.srb.core.mapper.DictMapper;
import com.zzg.srb.core.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author zhengzg
 * @since 2022-05-27
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 导入数据，当出现异常回滚事务
     * @param inputStream
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void exportDict(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("excel导入成功");
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dicts = baseMapper.selectList(null);
        List<ExcelDictDTO> collect = dicts.stream().map(dict -> {
            ExcelDictDTO dictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dict, dictDTO);
            return dictDTO;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        try {
            log.info("redis中获取数据列表");
            List<Dict> dataList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
            if (dataList != null) {
                return dataList;
            }
        } catch (Exception e) {
            //打印异常
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));
        }

        log.info("数据库中获取数据");
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId,parentId);

        List<Dict> dicts = baseMapper.selectList(wrapper);
        //判断是否有子节点
        dicts.forEach(dict -> dict.setHasChildren(hasChildren(dict.getParentId())));

        try {
            log.info("数据列表存入redis");
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId,dicts,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            //打印异常
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));
        }
        //数据存入redis
        return dicts;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getDictCode,dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        LambdaQueryWrapper<Dict> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper.eq(Dict::getDictCode,dictCode);

        Dict parentDict = baseMapper.selectOne(dictLambdaQueryWrapper);

        if (Objects.isNull(parentDict)){
            return "";
        }

        dictLambdaQueryWrapper = new LambdaQueryWrapper<>();

        dictLambdaQueryWrapper
                .eq(Dict::getParentId,parentDict.getId())
                .eq(Dict::getValue,value);

        Dict dict = baseMapper.selectOne(dictLambdaQueryWrapper);
        if (Objects.isNull(dict)){
            return "";
        }

        return dict.getName();

    }

    private Boolean hasChildren(Long parentId) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId,parentId);
        return baseMapper.selectCount(wrapper) > 0;
    }
}
